package com.lagou.filter;

import com.lagou.monitor.TPMonitorHolder;
import com.lagou.monitor.TPMonitorMeta;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.ArrayList;
import java.util.List;


/**
 * 题目要求：
 * 3. 利用TPMonitorFilter在消费端记录每个方法的请求耗时时间（异步调用不进行记录）
 */
@Activate(group = {CommonConstants.CONSUMER})
//@Activate(group = {CommonConstants.CONSUMER,CommonConstants.PROVIDER})
public class TPMonitorFilter implements Filter {
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime  = System.currentTimeMillis();
        try {
            // 执行方法
            return invoker.invoke(invocation);
        } finally {
            String methodName = invocation.getMethodName();
            String serviceName = invocation.getServiceName();
            System.out.println("服务名:" + invocation.getServiceName());
            System.out.println("方法：" + methodName);
            long costTime = (System.currentTimeMillis() - startTime);
            System.out.println("invoke time:"+ costTime + "毫秒");
            TPMonitorMeta meta = new TPMonitorMeta();
            meta.setServiceName(invocation.getServiceName());
            meta.setMethodName(methodName);
            meta.setCostTime(costTime);
            meta.setRequestTime(startTime);
            final String key = serviceName + "#" + methodName;
            if(!TPMonitorHolder.map.containsKey(key)) {
                List<TPMonitorMeta> metaList = new ArrayList<>();
                TPMonitorHolder.map.put(key, metaList);
            }
            List<TPMonitorMeta> metaList = TPMonitorHolder.map.get(key);
            metaList.add(meta);
        }

    }
}
